package com.dns.server.primary;

import java.util.concurrent.ConcurrentHashMap;

import com.dns.message.DNS_Message;

public class ServerRegistry {
	
	private static ConcurrentHashMap<String,SecondaryServerInfo> registerMap;
	
	static{
		registerMap = new ConcurrentHashMap<String, SecondaryServerInfo>();
	}
	

	public static void regiserSecondarServer(DNS_Message msg){
	
		String domainName = msg.getDomainName();
		String ipAddress = msg.getIp_address();
		int port = msg.getClientPort();
		SecondaryServerInfo server = new SecondaryServerInfo(domainName,ipAddress,port);
		if(registerMap.containsKey(domainName)){
			System.out.println("ServerRegistry : Info : Server all ready registered for this Domain name "+domainName+" Updating with the new entry"+ipAddress +" : "+port);
			registerMap.replace(domainName, server);
		}
		else {
			System.out.println("ServerRegistry : Info : Registring Secondary Server for Domain name "+domainName+" with the "+ipAddress +" : "+port);
		}
		registerMap.putIfAbsent(domainName, server);
	}
	
	public static SecondaryServerInfo getSecondaryServer(String domainName){
		if(domainName!=null){
			String domain=domainName.substring(domainName.lastIndexOf(".")+1);
			if(registerMap.containsKey(domain)){
				return registerMap.get(domain);
			}
			else{
				System.out.println("ServerRegistry : Error : No Secondary server mapped for this Domain name : "+domainName);
				return null;
			}
		}
		System.out.println("ServerRegistry : Error : Invalid Domain Name");
		return null;
	}
}
